import Vue from 'vue'
import VueRouter from 'vue-router'
import {userMenu} from "@/api/user";
import {listToTree} from "@/utils/treeUtil";
import store from "@/store";


Vue.use(VueRouter)

const routes = [

    {
        path: '/',
        redirect: '/login'
    },
    {
        path: '/login',
        component: () => import('@/views/login/LoginView.vue'),
        name: 'login'
    },
    {
        path: "/index",
        component: () => import('@/views/layout/IndexView.vue'),
        name: 'indexView',
        redirect: '/home',
        children: [ ]
    }
]

const router = new VueRouter({
    routes
})


//路由守卫
router.beforeEach(async (to, from, next) => {
    // 获取用户的菜单数据
    let token = sessionStorage.getItem("token");

    if (token && to.path=='/login'){
        next("/home")
    }

    if (!token && to.path!="/login"){
        next("/login")
    }


    if (token) {  // 判定用户是否登录  true
        if (store.state.menuData.length == 0) {  // 判定用户的菜单数据是否已经存在
            let {data} = await userMenu()
            let menu = [
                {
                    title: '首页',
                    icon: 'el-icon-menu',
                    path: '/home'
                },
                ...listToTree(data.permissions)
            ]

            // 调用initMenu 实现menuData数据的设置
            store.commit('initMenu', menu);

            // 生成动态路由
            let menuRouter = data.permissions.filter(permission => permission.isMenu == 1)
                .map(permission => {
                    return {
                        path: permission.path,
                        component: () => import('@/views/' + permission.model + '/' + permission.component),
                    }
                })

            let newRouter = [
                {
                    path: '/home',
                    component: () => import('@/views/home/HomeView.vue'),
                    name: 'home'
                },
                ...menuRouter,
                {
                    path: '/**',
                    component: () => import('@/views/page404/Page404View.vue'),
                    name: 'page404'
                },
            ]

            //遍历路由数组 添加路由到根路由
            newRouter.forEach(nrt => {
                router.addRoute('indexView', nrt)
            })
            // 重新跳转
            next(to.path)
        }
    }
    next()
})

export default router
